<?php
namespace Popshouse\SiteBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Popshouse\SiteBundle\Form\EntryForm;
use Popshouse\SiteBundle\Entity\Entry;
use Symfony\Component\HttpFoundation\Response;


/**
 * 
 */
class GuestbookController extends Controller
{

	/**
     * @extra:Template()
     */
    public function indexAction()
    {
    	$em = $this->get('doctrine.orm.entity_manager');
    	$query = $em->createQuery("SELECT e FROM Popshouse\SiteBundle\Entity\Entry e WHERE e.parent IS NULL ORDER BY e.datum DESC");
		$entries = $query->getResult();
        return array('entries' => $entries);
    }
    
     public function deleteAction($entry = 0){
		$em = $this->get('doctrine.orm.entity_manager');
        $entry = $em->find('Popshouse\SiteBundle\Entity\Entry', $entry);
        if($entry===null || !$entry->getId())
           throw new \Exception("Dit bericht werd niet gevonden");

        foreach($entry->getChildren() as $child){
        	$em->remove($child);
        }
        
        $em->remove($entry);
        $em->flush();
        
         return new Response(json_encode(array('message'=>'Verwijdert')));
        
    }
    

    
    /**
     * @extra:Template()
     */
    public function signAction($comment = 0){
    	$original = null;
    	if($comment != 0){
    		$em = $this->get('doctrine.orm.entity_manager');
    		$original = $em->find('Popshouse\SiteBundle\Entity\Entry', $comment);
    		if($original === null || $original->getParent() !== null){
    			throw new Exception("U kunt niet reageren");
    		}
    	}
    	
    	$entry = new Entry();
    	
    	//$form = EntryForm::create($this->get('form.context'), 'entry', array('translator' => $this->get('translator')));
     	$form = $this->get('form.factory')->createNamed(new EntryForm(),'entry',$entry);
        $request = $this->get('request');
	    if ($request->getMethod() == 'POST') {
	        $form->bindRequest($request);
	
	        if ($form->isValid()) {
 
	        	$entry->setIp($request->getClientIp());
	        	$entry->setAdmin((boolean) $this->container->get('security.context')->isGranted('ROLE_ADMIN'));
	        	$entry->setDatum(time());
	
	
		  		$em = $this->get('doctrine.orm.entity_manager');
		        $em->persist($entry);
		        
		        if($original !== null){
		        	$entry->setParent($original);
		        }
	
		        $em->flush();
	            
		        $this->get('session')->setFlash('notice', $this->get('translator')->trans('bericht.toegevoegd', array(), 'guestbook'));
	           	return new RedirectResponse($this->generateUrl('guestbook'));
        	}
	    }
  
        return array('form' => $form->createView(), 'original' => $original, 'comment' => $comment);
    }
}